package com.sohh.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sohh.entity.Users;
import com.sohh.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description: 自定义实现类完成账号密码的设置
 * @author: ruoan
 * @date: 2021/2/5 15:37
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //List<GrantedAuthority> perms = AuthorityUtils.commaSeparatedStringToAuthorityList("root");
        //return new User("mary", passwordEncoder.encode("123456"), perms);



        // 查询数据库，返回UserDetails示例，完成用户认证功能
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        Users user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            //认证失败
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<GrantedAuthority> perms = AuthorityUtils.commaSeparatedStringToAuthorityList("happy,ROLE_admin");


        // 注意这里的第二个参数不是密码，而是密码经过加密后的字符串
        return new User(user.getUsername(),passwordEncoder.encode(user.getPassword()),perms);
        //return new User(user.getUsername(),user.getPassword(),perms);

    }
}
